package com.hz.friends.sound;

import java.io.File;
import java.io.IOException;

import com.hz.friends.global.Global;

import android.media.MediaRecorder;
import android.os.Environment;

public class SoundMeter {
	static final private double EMA_FILTER = 0.6;

	private MediaRecorder mRecorder = null;
	private double mEMA = 0.0;
	private final String voicedir = android.os.Environment
			.getExternalStorageDirectory() + "/" + Global.productName + "/";
	private int maxduration = 60 * 1000;
	private boolean isrecording = false;
	private String name = null;
	private double voiceduration = 0;

	public String getVoiceDir() {
		return voicedir;
	}
	
	public String getVoicePath(){
		return voicedir+name;
	}

	public boolean isRecording() {
		return isrecording;
	}
	
	public String getName(){
		return name;
	}
    
	public void setName(String name){
        this.name = name;
	}
	public double getVoiceduration() {
		return voiceduration;
	}

	public void setVoiceduration(double voiceduration) {
		this.voiceduration = voiceduration;
	}

	public void start(String name) {
		if (!Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			return;
		}
		if (mRecorder == null) {
			mRecorder = new MediaRecorder();
			mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			mRecorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
			mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			mRecorder.setOutputFile(voicedir + name);
			mRecorder.setMaxDuration(maxduration);
			this.name = name;
			try {
				mRecorder.prepare();
				mRecorder.start();
				isrecording = true;
				mEMA = 0.0;
			} catch (Exception e) {
				e.printStackTrace();
				isrecording = false;
			}

		}
	}

	public SoundMeter() {
		File file = new File(voicedir);
		if (!file.exists()) {
			file.mkdir();
		}

	}

	public void stop() {
		try {
			if (mRecorder != null) {
					mRecorder.stop();
					mRecorder.release();
					mRecorder = null;
					isrecording = false;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void pause() {
		if (mRecorder != null) {
			mRecorder.stop();
		}
	}

	public void start() {
		if (mRecorder != null) {
			mRecorder.start();
		}
	}

	public double getAmplitude() {
		if (mRecorder != null)
			return (mRecorder.getMaxAmplitude() / 2700.0);
		else
			return 0;

	}

	public double getAmplitudeEMA() {
		double amp = getAmplitude();
		mEMA = EMA_FILTER * amp + (1.0 - EMA_FILTER) * mEMA;
		return mEMA;
	}
}
